import logging
import os

from dotenv import load_dotenv

from service.token_service import get_token

load_dotenv()

MCP_SERVER_NAME = "ZenTao"

# 日志配置
# 1. 写入文件配置
logging.basicConfig(
    format='%(asctime)s %(filename)s %(levelname)s : %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    filename="server.log",  # log文件名
    filemode='a',
    level=logging.DEBUG
)
# 2. 控制台输出配置
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(filename)s %(levelname)s : %(message)s',
                              '%Y-%m-%d %H:%M:%S')  # 定义该handler格式
console.setFormatter(formatter)
logging.getLogger().addHandler(console)  # 实例化添加handler

# 日志
logger = logging.getLogger(MCP_SERVER_NAME)

# 解析环境变量
SERVER_PORT = os.getenv("PORT", 8000)

BASE_URL = os.getenv("ZENTAO_URL", "http://127.0.0.1/zentao/api.php/v1")
USERNAME = os.getenv("ZENTAO_USERNAME")
PASSWORD = os.getenv("ZENTAO_PASSWORD")
ENV_TOKEN = os.getenv("ZENTAO_TOKEN")

TOKEN = None

if ENV_TOKEN is None:
    if USERNAME is None:
        raise ValueError("ZENTAO_USERNAME environment variable required")
    if PASSWORD is None:
        raise ValueError("ZENTAO_PASSWORD environment variable required")
    TOKEN = get_token(BASE_URL, USERNAME, PASSWORD)
else:
    TOKEN = ENV_TOKEN

# 请求头
HEADER = {
    "Token": TOKEN
}
